<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>变量和函数-kotlin基础(二) | Hexo</title><meta name="keywords" content="kotlin基础"><meta name="author" content="Joey"><meta name="copyright" content="Joey"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="一、变量和函数变量：变量声明 ： val &#x2F; var  val  (value简写)不可变变量：初始赋值后不可更改   对应java中 final 关键字    var（variable简写） 可变变量   类型推导机制：整数赋给变量a, 则 a 自动推导为整数。 变量若延迟赋值： 类型无法自动推导。需要显示声明类型  val a: Int &#x3D; 10   注：java  基本数据类型全小写， Ko">
<meta property="og:type" content="article">
<meta property="og:title" content="变量和函数-kotlin基础(二)">
<meta property="og:url" content="https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_base/index.html">
<meta property="og:site_name" content="Hexo">
<meta property="og:description" content="一、变量和函数变量：变量声明 ： val &#x2F; var  val  (value简写)不可变变量：初始赋值后不可更改   对应java中 final 关键字    var（variable简写） 可变变量   类型推导机制：整数赋给变量a, 则 a 自动推导为整数。 变量若延迟赋值： 类型无法自动推导。需要显示声明类型  val a: Int &#x3D; 10   注：java  基本数据类型全小写， Ko">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg">
<meta property="article:published_time" content="2022-10-14T06:38:41.000Z">
<meta property="article:modified_time" content="2022-10-14T14:00:32.359Z">
<meta property="article:author" content="Joey">
<meta property="article:tag" content="kotlin基础">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg"><link rel="shortcut icon" href="/blog/img/favicon.png"><link rel="canonical" href="https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_base/"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/blog/css/index.css"><link rel="stylesheet" href="https://unpkg.com/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://unpkg.com/@fancyapps/ui/dist/fancybox.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/blog/',
  algolia: undefined,
  localSearch: {"path":"/blog/search.xml","preload":false,"languages":{"hits_empty":"找不到您查询的内容：${query}"}},
  translate: {"defaultEncoding":2,"translateDelay":100,"msgToTraditionalChinese":"繁","msgToSimplifiedChinese":"简"},
  noticeOutdate: {"limitDay":180,"position":"top","messagePrev":"It has been","messageNext":"days since the last update, the content of the article may be outdated."},
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: undefined,
  source: {
    justifiedGallery: {
      js: 'https://unpkg.com/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://unpkg.com/flickr-justified-gallery/dist/fjGallery.css'
    }
  },
  isPhotoFigcaption: true,
  islazyload: false,
  isAnchor: true
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: '变量和函数-kotlin基础(二)',
  isPost: true,
  isHome: false,
  isHighlightShrink: false,
  isToc: true,
  postUpdate: '2022-10-14 22:00:32'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 5.4.2"></head><body><div id="loading-box"><div class="loading-left-bg"></div><div class="loading-right-bg"></div><div class="spinner-box"><div class="configure-border-1"><div class="configure-core"></div></div><div class="configure-border-2"><div class="configure-core"></div></div><div class="loading-word">加载中...</div></div></div><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="https://i.loli.net/2021/02/24/5O1day2nriDzjSu.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/blog/archives/"><div class="headline">文章</div><div class="length-num">21</div></a><a href="/blog/tags/"><div class="headline">标签</div><div class="length-num">26</div></a><a href="/blog/categories/"><div class="headline">分类</div><div class="length-num">30</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li></ul></div></div></div></div><div class="post" id="body-wrap"><header class="not-top-img" id="page-header"><nav id="nav"><span id="blog_name"><a id="site-name" href="/blog/">Hexo</a></span><div id="menus"><div id="search-button"><a class="site-page social-icon search"><i class="fas fa-search fa-fw"></i><span> 搜索</span></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/blog/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/blog/archives/"><i class="fa-fw fas fa-archive"></i><span> 时间轴</span></a></div><div class="menus_item"><a class="site-page" href="/blog/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/blog/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page group" href="javascript:void(0);"><i class="fa-fw fas fa-list"></i><span> 清单</span><i class="fas fa-chevron-down"></i></a><ul class="menus_item_child"><li><a class="site-page child" href="/blog/music/"><i class="fa-fw fas fa-music"></i><span> Music</span></a></li></ul></div></div><div id="toggle-menu"><a class="site-page"><i class="fas fa-bars fa-fw"></i></a></div></div></nav></header><main class="layout" id="content-inner"><div id="post"><div id="post-info"><h1 class="post-title">变量和函数-kotlin基础(二)</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2022-10-14T06:38:41.000Z" title="发表于 2022-10-14 14:38:41">2022-10-14</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2022-10-14T14:00:32.359Z" title="更新于 2022-10-14 22:00:32">2022-10-14</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/kotlin/">kotlin</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/kotlin/%E5%8F%98%E9%87%8F-%E5%87%BD%E6%95%B0/">变量&amp;函数</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/kotlin/%E6%9D%A1%E4%BB%B6%E8%AF%AD%E5%8F%A5-%E5%BE%AA%E7%8E%AF%E8%AF%AD%E5%8F%A5/">条件语句&amp;循环语句</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E7%AC%AC%E4%B8%80%E8%A1%8C%E4%BB%A3%E7%A0%81/">第一行代码</a><i class="fas fa-angle-right post-meta-separator"></i><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/blog/categories/%E7%AC%AC%E4%B8%80%E8%A1%8C%E4%BB%A3%E7%A0%81/kotlin/">kotlin</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">1.2k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>4分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="变量和函数-kotlin基础(二)"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div><article class="post-content" id="article-container"><h1 id="一、变量和函数"><a href="#一、变量和函数" class="headerlink" title="一、变量和函数"></a>一、变量和函数</h1><h2 id="变量："><a href="#变量：" class="headerlink" title="变量："></a>变量：</h2><h3 id="变量声明-：-val-var"><a href="#变量声明-：-val-var" class="headerlink" title="变量声明 ： val / var"></a><strong>变量声明</strong> ： val / var</h3><ul>
<li> <code>val</code>  (<code>value</code>简写)不可变变量：初始赋值后不可更改</li>
</ul>
<blockquote>
<p>对应<code>java</code>中 <code>final</code> 关键字</p>
</blockquote>
<ul>
<li> <code>var</code>（<code>variable</code>简写） 可变变量</li>
</ul>
<blockquote>
<p>类型推导机制：整数赋给变量<code>a</code>, 则 <code>a</code> <strong>自动推导</strong>为整数。</p>
<p>变量若延迟赋值： 类型无法自动推导。需要<strong>显示</strong>声明类型</p>
<ul>
<li><code>val a: Int = 10 </code></li>
</ul>
<p>注：<code>java </code> 基本数据类型全小写， <code>Kotlin</code> 首字母大写（表明其抛弃了<strong>基本</strong>数据类型，全部使用了<strong>对象</strong>数据<strong>类型</strong>）</p>
<blockquote>
<p>Int / Long / Short / Float/ Double / Boolean / <code>Char</code> 字符 /<code>Byte</code> 字节</p>
</blockquote>
</blockquote>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 示例：</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">main</span><span class="params">()</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> a: <span class="built_in">Int</span>=<span class="number">10</span></span><br><span class="line">    a= a * <span class="number">10</span></span><br><span class="line">    println(<span class="string">&quot;a=<span class="variable">$a</span>&quot;</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="函数：fun"><a href="#函数：fun" class="headerlink" title="函数：fun"></a>函数：fun</h2><h3 id="1-定义函数："><a href="#1-定义函数：" class="headerlink" title="1. 定义函数："></a>1. 定义函数：</h3><p><code>fun</code>关键字。参数可选，返回类型可选。</p>
<h3 id="2-参数声明："><a href="#2-参数声明：" class="headerlink" title="2. 参数声明："></a>2. 参数声明：</h3><p> <code>参数名 : 参数类型</code></p>
<h3 id="3-简写："><a href="#3-简写：" class="headerlink" title="3. 简写："></a>3. 简写：</h3><ul>
<li><p>当函数只有<strong>一行</strong>代码，可<strong>不写函数体</strong>，而直接将其写在<strong>尾部</strong>，用<strong>等号</strong>连接</p>
</li>
<li><p>``` kotlin<br>//示例：<br>package com.joey.mreader</p>
<p>import java.lang.Integer.max</p>
<p>fun main() {</p>
<pre><code>val a= 100
val b= 120
val value = largeNumber(a,b)
println(&quot;max:$value~~~~~~&quot;)
</code></pre>
<p>}</p>
<p>fun largerNumber(num1: Int, num2: Int):Int{  //声明函数：找两者间最大的整数</p>
<pre><code>return max(num1,num2)
</code></pre>
<p>}<br>//等同于 ↓<br>fun largerNumber2(num1: Int, num2: Int):Int = max(num1, num2)</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">### 4.函数的可见性修饰符：</span><br><span class="line"></span><br><span class="line">直接定义在 `fun` 关键字前面</span><br><span class="line"></span><br><span class="line">- `public`  (默认)，表示对**所有类**都可见</span><br><span class="line">- `private`  表示只对**当前类内部**可见</span><br><span class="line">- `protected` 只对**当前类和子类** 可见</span><br><span class="line">- `internal` 只对同一模块中的类可见( 如某些函数只允许在模块内调用，不暴露给外部，可将这些函数声明为 `internal`)</span><br><span class="line"></span><br><span class="line">对比图：</span><br><span class="line"></span><br><span class="line">![image-20221014144403520](https://gitee.com/Jonhsean/noteps/raw/master/20221014144403.png)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"># 二、逻辑控制</span><br><span class="line"></span><br><span class="line">`顺序语句`，`条件语句`，`循环语句`</span><br><span class="line"></span><br><span class="line">---</span><br><span class="line"></span><br><span class="line">## 条件语句： if / when</span><br><span class="line"></span><br><span class="line">### 1. `if` 语句</span><br><span class="line"></span><br><span class="line">####  与 `java`中不同点：</span><br><span class="line"></span><br><span class="line">- 它可以**有返回值**，返回值就是 if 语句**每一个条件**的**最后一行**代码的返回值。</span><br><span class="line"></span><br><span class="line">  - ``` kotlin</span><br><span class="line">    // 示例： 如找最大数</span><br><span class="line">    fun maxNumber(num1: Int, num2: Int): Int&#123;</span><br><span class="line">        var value = 0</span><br><span class="line">        if(num1 &gt; num2)&#123;</span><br><span class="line">            value = num1</span><br><span class="line">        &#125;else&#123;</span><br><span class="line">            value = num2</span><br><span class="line">        &#125;</span><br><span class="line">        return value</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br></pre></td></tr></table></figure>

<p>  <strong>返回值写法</strong>：</p>
  <figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 精简1</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">maxNumber</span><span class="params">(num1: <span class="type">Int</span>, num2: <span class="type">Int</span>)</span></span>: <span class="built_in">Int</span>&#123;</span><br><span class="line">    <span class="keyword">val</span> value = <span class="keyword">if</span>(num1 &gt; num2)&#123;  <span class="comment">// 0  且变量声明也改为 val 了</span></span><br><span class="line">    <span class="comment">//这里可以直接返回if 而不需要 value变了</span></span><br><span class="line">        num1  <span class="comment">//1</span></span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        num2  <span class="comment">//2</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> value</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//精简2：直接返回 If</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">maxNumber</span><span class="params">(num1: <span class="type">Int</span>, num2: <span class="type">Int</span>)</span></span>: <span class="built_in">Int</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">if</span>(num1 &gt; num2)&#123;</span><br><span class="line">        num1</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        num2</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//精简3：函数语法糖，只有一行代码可直接 = 链接</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">maxNumber</span><span class="params">(num1: <span class="type">Int</span>, num2: <span class="type">Int</span>)</span></span> = <span class="keyword">if</span> (num1&gt;num2)&#123;</span><br><span class="line">    num1</span><br><span class="line">&#125;<span class="keyword">else</span> &#123;</span><br><span class="line">    nume2</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//精简4： 压缩一行</span></span><br><span class="line"><span class="function"><span class="keyword">fun</span> <span class="title">maxNumber</span><span class="params">(num1: <span class="type">Int</span>, num2: <span class="type">Int</span>)</span></span> = <span class="keyword">if</span> (num1&gt; num2) num1 <span class="keyword">else</span> num2</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="2-when语句-类似-java-switch语句-："><a href="#2-when语句-类似-java-switch语句-：" class="headerlink" title="2. when语句(类似 java switch语句)："></a>2. <code>when</code>语句(类似 <code>java</code> <code>switch</code>语句)：</h3><blockquote>
<p><code>java</code> 的<code>switch</code>不好用：</p>
<ol>
<li>条件必须是 整形/ 短整型 / 字符串。</li>
<li>每个case 条件后要加 <code>break</code> ，否则执行完当前 case 会将下面的每个case依次执行</li>
</ol>
</blockquote>
<hr>
<h4 id="1-基本"><a href="#1-基本" class="headerlink" title="1. 基本"></a>1. 基本</h4><p><code>when</code>允许传入一个<strong>任意类型</strong>的<strong>参数</strong>，结构体中条件格式：</p>
<p><code>匹配值 -&gt; &#123; 执行逻辑 &#125;</code></p>
<h4 id="2-4个特点"><a href="#2-4个特点" class="headerlink" title="2. 4个特点"></a>2. 4个特点</h4><ul>
<li><p><code>when</code> 同 <code>if</code>，<strong>可以有返回值</strong>。使用单行代码函数语法糖</p>
</li>
<li><p>当只有执行逻辑只有一行代码， <code>&#123;&#125;</code>可以省略</p>
<ul>
<li>``` kotlin<br>// 查成绩<br>fun getScore(name: String) = when (name) { //单行代码语法糖<pre><code>&quot;Tom&quot; -&gt; 86
&quot;Jim&quot; -&gt; 77
&quot;Jack&quot;-&gt; 95
else  -&gt; 0
</code></pre>
}<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">  - </span><br><span class="line"></span><br><span class="line">- 除了精确匹配，还允许进行 **类型匹配**，通过 `is`关键字</span><br><span class="line"></span><br><span class="line">  - ``` kotlin</span><br><span class="line">    //判断数字类型</span><br><span class="line">    fun checkNumber(num: Number)&#123; //Number是内置的抽象类，数字相关的都是它的子类</span><br><span class="line">        when(num)&#123;</span><br><span class="line">            is Int -&gt; println(&quot;number is Int&quot;)</span><br><span class="line">            is Double -&gt; println(&quot;number is Double&quot;)</span><br><span class="line">            else -&gt; println(&quot;number not support&quot;)</span><br><span class="line">        &#125;</span><br><span class="line">         </span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
<li><p><code>when</code> 不带参数的用法，扩展性强</p>
<ul>
<li>``` kotlin<br>// 查成绩<br>fun getScore(name: String) = when{<pre><code>name.starWith(&quot;Tom&quot;) -&gt;86  //以Tom开头的成绩都是86 （扩展性）
name == &quot;Jim&quot;-&gt;77
name == &quot;Jack&quot;-&gt;95
else -&gt; 0
</code></pre>
}<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">---</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">## 循环语句：while / for</span><br><span class="line"></span><br><span class="line">### 一、 `while` 用法没有区别，略过</span><br><span class="line"></span><br><span class="line">### 二、 `for` 循环</span><br><span class="line"></span><br><span class="line">&gt; `Java` 中 `for - i` 循环直接被其舍弃了，`for-each` 被大幅加强，变为了 `for- in`</span><br><span class="line"></span><br><span class="line">重点学习 -》  `Kotlin` : `for - in` 循环</span><br><span class="line"></span><br><span class="line">#### ①. `区间`的概念：</span><br><span class="line"></span><br><span class="line">  `val range = 0..10`  </span><br><span class="line"></span><br><span class="line">#### ② `区间`的4个关键字：</span><br><span class="line"></span><br><span class="line">&gt; - `..` 创建闭区间为关键字， 相当于数学的 `[0,10]`</span><br><span class="line">&gt;</span><br><span class="line">&gt; - `until`  创建左必右开区间关键字， 相当于数学 `[0,10)` </span><br><span class="line">&gt;   - 代码： `val range = 0 until 10`</span><br><span class="line">&gt; - `step` 跳过元素关键字，</span><br><span class="line">&gt;   - 代码：`for( i in 0 until 10 step 2)&#123;...&#125;`  相当于 `[0,10)  i=i+2`</span><br><span class="line">&gt; - `downTo`**降序**关键字 【前面的 `..`和 `until` 都是**升序**区间】</span><br><span class="line">&gt;   - 代码： `for(i in 10 downTo 1)&#123;...&#125;` 相当于 [10 , 1]</span><br><span class="line"></span><br><span class="line">#### ③用途：</span><br><span class="line"></span><br><span class="line">- for - in 循环 可以用于遍历`区间`，`数组`和`集合`</span><br><span class="line"></span><br><span class="line">``` kotlin</span><br><span class="line">//例如:</span><br><span class="line">fun main()&#123;</span><br><span class="line">    for(i in 0..10)&#123;</span><br><span class="line">        println(i)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></li>
</ul>
</li>
</ul>
<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://jonhsean.gitee.io/blog">Joey</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_base/">https://jonhsean.gitee.io/blog/2022/10/14/daily/kotlin_base/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://jonhsean.gitee.io/blog" target="_blank">Hexo</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/blog/tags/kotlin%E5%9F%BA%E7%A1%80/">kotlin基础</a></div><div class="post_share"><div class="social-share" data-image="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://unpkg.com/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://unpkg.com/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/blog/2022/10/14/daily/kotlin_info/"><img class="prev-cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">介绍-kotlin基础(一)</div></div></a></div><div class="next-post pull-right"><a href="/blog/2022/10/14/daily/kotlin_oop/"><img class="next-cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" onerror="onerror=null;src='/blog/img/404.jpg'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">面向对象1-kotlin基础(三)</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/blog/2022/10/14/daily/kotlin_classSPEC/" title="面向对象3:数据类和单例类-kotlin基础(三)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">面向对象3:数据类和单例类-kotlin基础(三)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_info/" title="介绍-kotlin基础(一)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">介绍-kotlin基础(一)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_interface/" title="面向对象2:接口-kotlin基础(三)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">面向对象2:接口-kotlin基础(三)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_lambda%E7%BC%96%E7%A8%8B/" title="Lambda编程-kotlin基础(四)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">Lambda编程-kotlin基础(四)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_oop/" title="面向对象1-kotlin基础(三)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">面向对象1-kotlin基础(三)</div></div></a></div><div><a href="/blog/2022/10/14/daily/kotlin_%E5%B0%8F%E9%AD%94%E6%9C%AF/" title="小技巧-kotlin基础(六)"><img class="cover" src="https://i.loli.net/2020/05/01/gkihqEjXxJ5UZ1C.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2022-10-14</div><div class="title">小技巧-kotlin基础(六)</div></div></a></div></div></div></div><div class="aside-content" id="aside-content"><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#%E4%B8%80%E3%80%81%E5%8F%98%E9%87%8F%E5%92%8C%E5%87%BD%E6%95%B0"><span class="toc-text">一、变量和函数</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%EF%BC%9A"><span class="toc-text">变量：</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%8F%98%E9%87%8F%E5%A3%B0%E6%98%8E-%EF%BC%9A-val-var"><span class="toc-text">变量声明 ： val &#x2F; var</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%87%BD%E6%95%B0%EF%BC%9Afun"><span class="toc-text">函数：fun</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-%E5%AE%9A%E4%B9%89%E5%87%BD%E6%95%B0%EF%BC%9A"><span class="toc-text">1. 定义函数：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-%E5%8F%82%E6%95%B0%E5%A3%B0%E6%98%8E%EF%BC%9A"><span class="toc-text">2. 参数声明：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#3-%E7%AE%80%E5%86%99%EF%BC%9A"><span class="toc-text">3. 简写：</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-when%E8%AF%AD%E5%8F%A5-%E7%B1%BB%E4%BC%BC-java-switch%E8%AF%AD%E5%8F%A5-%EF%BC%9A"><span class="toc-text">2. when语句(类似 java switch语句)：</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#1-%E5%9F%BA%E6%9C%AC"><span class="toc-text">1. 基本</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#2-4%E4%B8%AA%E7%89%B9%E7%82%B9"><span class="toc-text">2. 4个特点</span></a></li></ol></li></ol></li></ol></li></ol></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2022 By Joey</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="translateLink" type="button" title="简繁转换">繁</button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><i class="fas fa-arrow-up"></i></button></div></div><div id="local-search"><div class="search-dialog"><nav class="search-nav"><span class="search-dialog-title">搜索</span><span id="loading-status"></span><button class="search-close-button"><i class="fas fa-times"></i></button></nav><div class="is-center" id="loading-database"><i class="fas fa-spinner fa-pulse"></i><span>  数据库加载中</span></div><div class="search-wrap"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章" type="text"/></div></div><hr/><div id="local-search-results"></div></div></div><div id="search-mask"></div></div><div><script src="/blog/js/utils.js"></script><script src="/blog/js/main.js"></script><script src="/blog/js/tw_cn.js"></script><script src="https://unpkg.com/@fancyapps/ui/dist/fancybox.umd.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://unpkg.com/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><script src="/blog/js/search/local-search.js"></script><script>var preloader = {
  endLoading: () => {
    document.body.style.overflow = 'auto';
    document.getElementById('loading-box').classList.add("loaded")
  },
  initLoading: () => {
    document.body.style.overflow = '';
    document.getElementById('loading-box').classList.remove("loaded")

  }
}
window.addEventListener('load',preloader.endLoading())</script><div class="js-pjax"></div><script defer="defer" id="fluttering_ribbon" mobile="true" src="https://unpkg.com/butterfly-extsrc/dist/canvas-fluttering-ribbon.min.js"></script><script src="https://unpkg.com/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = true;
document.body.addEventListener('input', POWERMODE);
</script><script id="click-heart" src="https://unpkg.com/butterfly-extsrc/dist/click-heart.min.js" async="async" mobile="true"></script><script src="https://unpkg.com/pjax/pjax.min.js"></script><script>let pjaxSelectors = ["head > title","#config-diff","#body-wrap","#rightside-config-hide","#rightside-config-show",".js-pjax"]

var pjax = new Pjax({
  elements: 'a:not([target="_blank"]):not([href="/music/"]):not([href="/no-pjax/"])',
  selectors: pjaxSelectors,
  cacheBust: false,
  analytics: false,
  scrollRestoration: false
})

document.addEventListener('pjax:send', function () {

  // removeEventListener scroll 
  window.tocScrollFn && window.removeEventListener('scroll', window.tocScrollFn)
  window.scrollCollect && window.removeEventListener('scroll', scrollCollect)

  typeof preloader === 'object' && preloader.initLoading()
  document.getElementById('rightside').style.cssText = "opacity: ''; transform: ''"
  
  if (window.aplayers) {
    for (let i = 0; i < window.aplayers.length; i++) {
      if (!window.aplayers[i].options.fixed) {
        window.aplayers[i].destroy()
      }
    }
  }

  typeof typed === 'object' && typed.destroy()

  //reset readmode
  const $bodyClassList = document.body.classList
  $bodyClassList.contains('read-mode') && $bodyClassList.remove('read-mode')

  typeof disqusjs === 'object' && disqusjs.destroy()
})

document.addEventListener('pjax:complete', function () {
  window.refreshFn()

  document.querySelectorAll('script[data-pjax]').forEach(item => {
    const newScript = document.createElement('script')
    const content = item.text || item.textContent || item.innerHTML || ""
    Array.from(item.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value))
    newScript.appendChild(document.createTextNode(content))
    item.parentNode.replaceChild(newScript, item)
  })

  GLOBAL_CONFIG.islazyload && window.lazyLoadInstance.update()

  typeof chatBtnFn === 'function' && chatBtnFn()
  typeof panguInit === 'function' && panguInit()

  // google analytics
  typeof gtag === 'function' && gtag('config', '', {'page_path': window.location.pathname});

  // baidu analytics
  typeof _hmt === 'object' && _hmt.push(['_trackPageview',window.location.pathname]);

  typeof loadMeting === 'function' && document.getElementsByClassName('aplayer').length && loadMeting()

  // prismjs
  typeof Prism === 'object' && Prism.highlightAll()

  typeof preloader === 'object' && preloader.endLoading()
})

document.addEventListener('pjax:error', (e) => {
  if (e.request.status === 404) {
    pjax.loadUrl('/404.html')
  }
})</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>